package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryShopList() {
        //提前创建一个key值，将"cache:shoptype:"封装为一个常量，放在RedisConstants中
        String key =  CACHE_SHOPTYPE_KEY;

        //1.从redis查询商铺类型缓存
        List<String> shopTypeList =new ArrayList<>();
        shopTypeList = stringRedisTemplate.opsForList().range(key,0,-1);
        //2.判断是否存在
        if (!shopTypeList.isEmpty()) {
            //3.存在，直接返回
            //将shopTypeJson转换为shopType实体类型
            //创建一个新的List，存放shopType实体类型
            List<ShopType> typeList = new ArrayList<>();
            for (String  s:shopTypeList) {
                ShopType shopType = JSONUtil.toBean(s, ShopType.class);
                typeList.add(shopType);
            }
            return Result.ok(typeList);
        }

        //4.不存在，根据分类查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //5.不存在，返回错误
        if (typeList.isEmpty()) {
            return Result.fail("不存在该分类！");
        }
        //6.添加该分类进数据库
        for (ShopType shopType:typeList) {
            //将该分类类型转换为字符串形式，放入数据库List中
            String s = JSONUtil.toJsonStr(shopType);
            shopTypeList.add(s);
        }
        //6.存在，写入redis   ，以List形式，从右边直接全部推入
        stringRedisTemplate.opsForList().rightPushAll(key,shopTypeList);
        //7.返回
        return Result.ok(typeList);
    }
}
